package org.csu.demo.db.Controller;

import jakarta.servlet.http.HttpSession;
import org.csu.demo.db.domain.Students;
import org.csu.demo.db.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;


@Controller
public class LoginController {
    @Autowired
    private StudentService studentService;

    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }

    @PostMapping("/login")
    public String login(@RequestParam String id,
                        @RequestParam String name,
                        HttpSession session,
                        Model model) {
        Students student = studentService.getStudentById(id);
        if (student != null && student.getName().equals(name)) {
            session.setAttribute("currentUser", student);
            return "redirect:/students";
        } else {
            model.addAttribute("error", "学号或姓名不正确");
            return "login";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("currentUser");
        return "redirect:/login";
    }
}
